<template>
    <el-container>
      <el-header class="query-container">
        <div class="query-box">
          <el-row class="row-bg" justify="space-evenly">
            <el-col :span="6"><div class="grid-content ep-bg-purple" />
              姓名 &nbsp; <el-input v-model="nameValue" style="width: 240px" placeholder="输入你的大名" />
            </el-col>
            <el-col :span="6"><div class="grid-content ep-bg-purple-light" />
              性别 &nbsp;<el-select
                  v-model="sexValue"
                  clearable
                  placeholder="性别"
                  style="width: 240px"
              >
                <el-option
                    v-for="item in sexOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6"><div class="grid-content ep-bg-purple" />
              角色 &nbsp;<el-select
                  v-model="roleValue"
                  clearable
                  placeholder="输入你的角色"
                  style="width: 240px"
              >
                <el-option
                    v-for="item in roleOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                />
              </el-select>
            </el-col>
            <el-col :span="6"><div class="grid-content ep-bg-purple" />
              <el-button type="primary" @click="queryUser()">查询</el-button>
            </el-col>
          </el-row>
        </div>
      </el-header>
      <el-divider />
      <el-main class="main-container">
          <el-table :data="userListData" style="width: 100%" :scrollbar-always-on="false" v-loading="userTableLoading">
            <el-table-column v-if="false" prop="id" label="id" width="0" />
            <el-table-column fixed prop="userName" label="姓名" width="180" />
            <el-table-column prop="userRole" label="角色"  width="180"/>
            <el-table-column prop="userAccount" label="账号"  width="180" />
            <el-table-column prop="email" label="邮箱"  width="160" />
            <el-table-column prop="sex" label="性别" width="100" />
            <el-table-column prop="userProfile" label="用户描述" width="250" />
            <el-table-column fixed="right" label="操作">
              <template #default="{row}">
                <el-button link type="primary" size="large" @click="userDetail(row.id)"
                >查看</el-button>
                <el-popover v-if="loginUserRole === 1"  trigger="click" placement="top" :width="160">
                  <el-radio-group v-model="userRoleValue">
                    <el-radio value="0">普通用户</el-radio>
                    <el-radio value="1">管理员</el-radio>
                    <el-radio value="2">禁用</el-radio>
                  </el-radio-group>
                  <div style="text-align: right; margin: 0">
                    <el-button size="small" type="primary" @click="setUserRole(row.id)">确认</el-button
                    >
                  </div>
                  <template #reference>
                    <el-button link type="primary" size="large">设置角色</el-button>
                  </template>
                </el-popover>
              </template>
            </el-table-column>
          </el-table>
      </el-main>
    </el-container>
    <div class="pagination-container">
      <el-pagination
          :page-size="pageSize"
          layout="prev, pager, next"
          :total="totalRow"
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog visible="true" width="30%">
      <img :src="currentAvatar" alt="用户头像" style="width: 100%" />
    </el-dialog>
</template>

<script setup>

import {onMounted, ref,reactive} from "vue";
import myAxios from "../../../plugins/myAxios.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();

const currentPage = ref(1);  //当前页
const totalRow = ref(0); //总页数
const pageSize = ref(10); //当前显示条数
const userRoleValue = ref(0);

const loginUserRole = ref(0)

const sexValue = ref('')
const roleValue = ref('')
const nameValue = ref('')
const sexOptions = [
  {
    value: 0,
    label: '男的',
  },
  {
    value: 1,
    label: '女的',
  }
]
const roleOptions = [
  {
    value: 0,
    label: '普通用户',
  },
  {
    value: 1,
    label: '超级管理员',
  }
]
const userListData = ref([
]);
const userTableLoading = ref(true);
const state = reactive({
  fits: ['fill', 'contain', 'cover', 'none', 'scale-down'],
  url: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg',
})
const currentAvatar = ref(''); //当前用户
const avatarDialogVisible  = ref(false);

onMounted(() =>{
  getUserInfo();
})

/**
 * 用户头像弹出框
 * @param url
 */
const showAvatarDialog = (url) => {
  console.log(url)
  avatarDialogVisible.value = true;
  currentAvatar.value = url;
}

/**
 * 设置用户权限
 * @param userId
 */
const setUserRole =(userId) => {
  myAxios.post('/user/setPermission',{
    id:userId,
    userRole:userRoleValue.value
  }).then(res => {
    ElMessage.success("设置成功");
    location.reload();
  }).catch(error => {
    ElMessage.error(error);
  })

}

/**
 * 查看用户详情
 * @param userId
 */
const userDetail = (userId) => {
  router.push({path: '/userIndex/userInfo',replace:true, state: { userId:userId }});
}

const queryUser = () => {
  userTableLoading.value = true;
  getUserInfo();
}

/**
 * 获取用户列表
 * @returns {Promise<void>}
 */
const getUserInfo =  () =>{
  myAxios.post('/user/list/page',{
    userName:nameValue.value,
    sex:sexValue.value,
    userRole:roleValue.value,
    current:currentPage.value,
    pageSize:pageSize.value
  }).then(res => {
    userListData.value = res.data;
    currentPage.value = res.current;
    pageSize.value = res.pageSize;
    totalRow.value = res.total;
    handleUserInfoData(userListData)
    new Promise(() => {
      getLoginUser();
    })
  }).catch(error => {
    ElMessage.error(error)
  }).finally(() => {
    userTableLoading.value = false;
  })
}

const getLoginUser = () => {
    // if(userId !== undefined && userId != null){
    //   console.log(userId)
    // }
    myAxios.post('/user/get').catch(() => {
      ElMessage({
        type: 'error',
        message: '服务器内部错误',
      })
    }).then(res => {
      loginUserRole.value = res.userRole;
    }).catch(error => {
      ElMessage.error(error);
    });
}

/**
 * 处理用户性别
 * @param userListData
 */
const handleUserInfoData = (userListData) => {
  for (let i = 0; i < userListData.value.length; i++) {
    let sex = userListData.value[i].sex;
    let sexName = "";
    if(sex === 0){
      sexName = '男';
    }else if(sex === 1){
      sexName = '女';
    }
    userListData.value[i].sex = sexName;
  }
}

/**
 * 分页查询
 * @param currentPageNumber
 */
const handleCurrentChange = (currentPageNumber) => {
  currentPage.value = currentPageNumber;
  getUserInfo()
}



</script>

<style scoped lang="less">

.common-layout{
  //overflow:hidden;
  //height: 100%;
}

.query-container{
  z-index: 999;
  width: 100%;
  margin:-10px 0 10px 30px;
  .query-box{

  }
}

.main-container{
  width: 100%;
  height: 100%;
  //background: blue;
  padding: 0;
  margin-top: -25px;
  margin-left: 20px;
}

.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}

.pagination-container{
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

</style>
